package com.xtravel.common.api;

import android.util.Log;
import com.google.gson.Gson;
import com.xtravel.common.helper.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BaseRequest {
    static final String TAG = "ApiRequest";
    static final String BASE_URL = "http://121.41.88.34/api/app";
//    static final String BASE_URL = "http://192.168.0.106./api/app";

    public String api(String url, Object... args) {
        url = getAbsoluteUrl(url);

        String requestUrl = url.replaceAll("\\?", "%s");
        requestUrl = String.format(requestUrl, args);

        return httpGet(requestUrl, null);
    }

    private String httpGet(String url, Map<String, String> args) {
        try {
            String serverUrl = createUrl(url, args);
            HttpGet request = new HttpGet(serverUrl);
            if (UserContext.IsSignin()) {
                request.setHeader("token", UserContext.GetCurrentToken().getToken());
            }
            HttpResponse response = new DefaultHttpClient().execute(request);
            if (response.getStatusLine().getStatusCode() < 500 && response.getStatusLine().getStatusCode() != 404) {
                return EntityUtils.toString(response.getEntity());
            } else {
                Log.d(TAG, String.format("response code:%s", response.getStatusLine().getStatusCode()));
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String HttpForm(String url, Map<String, String> args) {
        try {
            url = getAbsoluteUrl(url);
            HttpPost request = new HttpPost(url);
            if (UserContext.IsSignin()) {
                request.setHeader("token", UserContext.GetCurrentToken().getToken());
            }

            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : args.keySet()) {
                BasicNameValuePair param = new BasicNameValuePair(key, args.get(key));
                paramList.add(param);
            }

            request.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
            HttpResponse response = new DefaultHttpClient().execute(request);
            if (response.getStatusLine().getStatusCode() < 500 && response.getStatusLine().getStatusCode() != 404) {
                return EntityUtils.toString(response.getEntity());
            } else {
                Log.d(TAG, String.format("response code:%s", response.getStatusLine().getStatusCode()));
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String post(String url, Object params) {
        try {
            url = getAbsoluteUrl(url);
            HttpPost request = new HttpPost(url);
            if (UserContext.IsSignin()) {
                request.setHeader("token", UserContext.GetCurrentToken().getToken());
            }
            Gson gson = new Gson();
            String postdata = gson.toJson(params);
            Log.d(TAG, String.format("url:%s;data:%s", url, postdata));
            StringEntity jsonEntity = new StringEntity(postdata, HTTP.UTF_8);
            jsonEntity.setContentType("application/json");
            request.setEntity(jsonEntity);

            HttpResponse response = new DefaultHttpClient().execute(request);
            if (response.getStatusLine().getStatusCode() < 500 && response.getStatusLine().getStatusCode() != 404) {
                return EntityUtils.toString(response.getEntity());
            } else {
                Log.d(TAG, String.format("response code:%s", response.getStatusLine().getStatusCode()));
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public String post(String url, String postdata) {
        try {
            url = getAbsoluteUrl(url);
            HttpPost request = new HttpPost(url);
            if (UserContext.IsSignin()) {
                request.setHeader("token", UserContext.GetCurrentToken().getToken());
            }

            Log.d(TAG, String.format("url:%s;data:%s", url, postdata));
            StringEntity jsonEntity = new StringEntity(postdata, HTTP.UTF_8);
            jsonEntity.setContentType("application/json");
            request.setEntity(jsonEntity);

            HttpResponse response = new DefaultHttpClient().execute(request);
            if (response.getStatusLine().getStatusCode() < 500 && response.getStatusLine().getStatusCode() != 404) {
                return EntityUtils.toString(response.getEntity());
            } else {
                Log.d(TAG, String.format("response code:%s", response.getStatusLine().getStatusCode()));
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static String createUrl(String url, Map<String, String> args) {
        if (args == null) {
            return url;
        }

        url += "?";
        for (String key : args.keySet()) {
            url += key + "=" + args.get(key) + "&";
        }

        return url;
    }

    protected String getAbsoluteUrl(String partUrl) {
        if (!partUrl.startsWith("http")) {
            String host = BASE_URL;
            if (host.substring(BASE_URL.length() - 2).equals("/")) {
                host = BASE_URL.substring(0, BASE_URL.length() - 2);
            }
            if (partUrl.startsWith("/")) {
                return String.format("%s%s", BASE_URL, partUrl);
            } else {
                return String.format("%s/%s", BASE_URL, partUrl);
            }
        } else {
            return partUrl;
        }
    }

    protected String joinUrl(String... urls) {
        return StringUtils.join(urls, '/');
    }
}
